package com.example.mqttclient.weather;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.google.gson.Gson;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WeatherFetcher extends AsyncTask<Void, Void, SenseWeatherResponse> {
    private static final String TAG = "WeatherFetcher";
    private static final String API_KEY = "SWUDcW2SwKxrcF6rc"; // 替换为实际Key
    private static final String API_URL = "https://api.seniverse.com/v3/weather/now.json";

    private final Context context;
    private final WeatherCallback callback;

    public WeatherFetcher(Context context, WeatherCallback callback) {
        this.context = context;
        this.callback = callback;
    }

    @Override
    protected SenseWeatherResponse doInBackground(Void... voids) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(API_URL + "?key=" + API_KEY + "&location=beijing&language=zh-Hans&unit=c")
                    .build(); // 指定北京，中文，摄氏度

            Response response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                String json = response.body().string();
                Log.d(TAG, "心知天气响应: " + json);
                return new Gson().fromJson(json, SenseWeatherResponse.class);
            } else {
                Log.e(TAG, "请求失败，响应码: " + response.code());
            }
        } catch (Exception e) {
            Log.e(TAG, "请求失败: " + e.getMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(SenseWeatherResponse response) {
        if (response != null && response.results.length > 0 && response.results[0].now != null) {
            SenseWeatherResponse.Result.Now now = response.results[0].now;
            // 确保传递正确的参数名
            callback.onWeatherFetched(now.temperature, now.weatherText);
        }
    }

    public interface WeatherCallback {
        void onWeatherFetched(String temperature, String weatherText); // 与回调一致
    }
}